<template>
  <ContentWrap>
    <!-- 基本信息 -->
    <el-card class="mb-4">
      <template #header>
        <div class="card-header">
          <span class="font-medium">机构基本信息</span>
          <div class="right-button">
            <el-button type="primary" @click="handleSave">保存</el-button>
            <el-button @click="handleBack">返回</el-button>
          </div>
        </div>
      </template>
      <el-form ref="formRef" :rules="rules1" :model="detailData" label-width="120px" class="mt-4">
        <el-row :gutter="24">
          <el-col :span="8">
            <el-form-item label-width="180px" label="机构名称" prop="name">
              <el-input disabled v-model="detailData.name" placeholder="请输入机构名称" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label-width="180px" label="机构地址" prop="address">
              <el-input disabled v-model="detailData.address" placeholder="请输入机构地址" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label-width="180px" label="法人单位名称" prop="legalPersonCompany">
              <el-input
                disabled
                v-model="detailData.legalPersonCompany"
                placeholder="请输入法人单位名称"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item
              label="统一社会信用代码"
              prop="unifiedSocialCreditIdentifier"
              label-width="180px"
            >
              <el-input
                disabled
                v-model="detailData.unifiedSocialCreditIdentifier"
                placeholder="请输入统一社会信用代码"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label-width="180px" label="机构管理员" prop="manager">
              <el-input disabled v-model="detailData.manager" placeholder="请输入机构管理员" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label-width="180px" label="联系方式" prop="managerPhone">
              <el-input v-model="detailData.managerPhone" placeholder="请输入联系方式" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label-width="180px" label="机构简介" prop="summary">
              <el-input
                v-model="detailData.summary"
                type="textarea"
                :rows="4"
                placeholder="请输入机构简介"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <!-- 收样联系方式 -->
    <el-card class="mb-4">
      <template #header>
        <div class="card-header">
          <span class="font-medium">收样联系方式</span>
        </div>
      </template>
      <el-form
        ref="sampleFormRef"
        :rules="sampleFormRules"
        :model="detailData"
        label-width="120px"
        class="mt-4"
      >
        <el-row :gutter="24">
          <el-col :span="8">
            <el-form-item label-width="180px" label="联系人姓名" prop="receiveName">
              <el-input v-model="detailData.receiveName" placeholder="请输入联系人姓名" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label-width="180px" label="联系人电话" prop="receivePhone">
              <el-input v-model="detailData.receivePhone" placeholder="请输入联系人电话" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label-width="180px" label="联系人邮箱" prop="email">
              <el-input v-model="detailData.email" placeholder="请输入联系人邮箱" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label-width="180px" label="通讯地址" prop="mailingAddress">
              <el-input v-model="detailData.mailingAddress" placeholder="请输入通讯地址" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <!-- 机构资质 -->
    <el-card>
      <template #header>
        <div class="card-header">
          <span class="font-medium">机构资质</span>
          <div class="right-button">
            <el-button type="primary" @click="handleAddZz">新增</el-button>
          </div>
        </div>
      </template>
      <div style="max-height: 500px; overflow-y: auto">
        <el-table :data="qualificationList" :stripe="true" :show-overflow-tooltip="true">
          <el-table-column label="序号" type="index" width="80" align="center" />
          <el-table-column label="证书类型" align="center" prop="type">
            <template #default="scope">
              <span v-if="scope.row.type === 0">CMA </span>
              <span v-if="scope.row.type === 1">CNAS </span>
              <span v-if="scope.row.type === 2">体系证书</span>
            </template>
          </el-table-column>
          <el-table-column label="证书编号" align="center" prop="num" />
          <el-table-column label="发证机关" align="center" prop="licenceIssuingAuthority" />
          <el-table-column label="发证日期" align="center" prop="issueDate" />
          <el-table-column label="有效期至" align="center" prop="expireTime" />
          <!-- <el-table-column label="证件附件" align="center">
          <template #default="scope">
            <el-button link type="primary" @click="handleViewFile(scope.row)">上传附件</el-button>
          </template>
        </el-table-column> -->
        <el-table-column label="附件" align="center" >

          <template #default="scope">
          <span v-for="(link, index) in scope.row.attachment.split(';')" :key="index">
            <a href="#" @click.prevent="downloadFile(link)">{{ `附件${index + 1}` }}</a>
            <!-- 如果不是最后一个附件，添加逗号分隔 -->
            <span v-if="index < scope.row.attachment.split(';').length - 1">、</span>
          </span>
        </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="180">
            <template #default="scope">
              <el-button link type="primary" @click="handleEdit(scope.row)">编辑</el-button>
              <el-button link type="danger" @click="handleDelete1(scope.row)">删除</el-button>
           
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 新增/编辑弹窗 -->
      <el-dialog
        :title="dialogTitle"
        v-model="dialogVisible"
        v-if="dialogVisible"
        width="600px"
        append-to-body
        :before-close="beforeClose"
        :close-on-click-modal="false"
      >
        <el-form ref="dialogFormRef" :model="dialogData" label-width="100px" :rules="rules" inline>
          <el-form-item label="证书类型" prop="type">
            <el-select
              v-model="dialogData.type"
              placeholder="请选择证书类型"
              style="width: 100%"
              clearable
              class="!w50"
            >
              <el-option
                v-for="item in certificateTypes"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <!-- <el-form-item label="资质等级" prop="level">
            <el-input v-model="dialogData.level" placeholder="请输入资质等级" />
          </el-form-item> -->
          <el-form-item label="证书编号" prop="num">
            <el-input v-model="dialogData.num" placeholder="请输入证书编号" />
          </el-form-item>
          <el-form-item label="发证机关" prop="licenceIssuingAuthority">
            <el-input v-model="dialogData.licenceIssuingAuthority" placeholder="请输入发证机关" />
          </el-form-item>
          <el-form-item label="发证日期" prop="issueDate">
            <el-date-picker
              v-model="dialogData.issueDate"
              type="date"
              placeholder="请选择发证日期"
              style="width: 100%"
              value-format="YYYY-MM-DD"
              range-separator="至"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
            />
          </el-form-item>
          <el-form-item label="有效期至" prop="expireTime">
            <el-date-picker
              v-model="dialogData.expireTime"
              type="date"
              value-format="YYYY-MM-DD"
              placeholder="请选择有效期至"
              style="width: 100%"
              range-separator="至"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
            />
          </el-form-item>
          <el-form-item label="证书附件" prop="attachment">
            <el-upload
              action="#"
              :limit="5"
              :auto-upload="false"
              :file-list="fileList1"
              :before-upload="beforeUpload"
              :on-exceed="handleExceed"
              :on-change="handleFileSelect1"
              :before-remove="beforeRemove1"
              :accept="'image/png, image/jpeg, application/pdf, application/zip'"
              :on-preview="handlePreview"
              :on-remove="handleRemove1"
            >
              <template #tip>
                <div class="el-upload__tip">
                  请上传png、jpg、pdf、zip格式文件。大小不超过50M。
                </div>
              </template>
              <el-button type="primary">选择文件</el-button>
            </el-upload>
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="closeDialogJGZZ">取消</el-button>
            <el-button type="primary" @click="handleDialogSave">确定</el-button>
          </div>
        </template>
      </el-dialog>
    </el-card>

    <!-- 机构人员信息 -->
    <el-card class="mt-4">
      <template #header>
        <div class="card-header">
          <span class="font-medium">机构人员信息</span>
          <div class="right-button">
            <el-button type="primary" @click="handleAddStaff">新增</el-button>
          </div>
        </div>
      </template>
      <div style="max-height: 500px; overflow-y: auto">
        <el-table :data="staffList" :stripe="true" :show-overflow-tooltip="true">
          <el-table-column label="序号" width="80" type="index" align="center" />
          <el-table-column label="人员类型" align="center" prop="type">
            <template #default="scope">
              <span v-if="scope.row.type == 0">机构管理员</span>
              <span v-if="scope.row.type == 1">抽样人员</span>
              <span v-if="scope.row.type == 2">检验人员</span>
              <span v-if="scope.row.type == 3">技术审批人</span>
            </template>
          </el-table-column>
          <el-table-column label="姓名" align="center" prop="name" />
          <el-table-column label="性别" align="center" prop="gerden">
            <template #default="scope">
              <span v-if="scope.row.gerden == 0">女</span>
              <span v-else-if="scope.row.gerden == 1">男</span>
            </template>
          </el-table-column>
          <el-table-column label="身份证号" align="center" prop="identityCard" />
          <el-table-column label="邮箱" align="center" prop="email" />
          <el-table-column label="手机号" align="center" prop="phone" />
          <el-table-column label="是否在职" align="center" prop="isActive">
            <template #default="scope">
              {{ !scope.row.isOnJob ? '是' : '否' }}
            </template>
          </el-table-column>

          <el-table-column label="附件" align="center" >

<template #default="scope">


<span v-for="(link, index) in scope.row.attachment.split(';')" :key="index">
  <a href="#" @click.prevent="downloadFile(link)">{{ `附件${index + 1}` }}</a>
  <!-- 如果不是最后一个附件，添加逗号分隔 -->
  <span v-if="index < scope.row.attachment.split(';').length - 1">、</span>
</span>
</template>
</el-table-column>

          <el-table-column label="操作" align="center" width="180">
            <template #default="scope">
              <el-button link type="primary" @click="handleEditStaff(scope.row)">编辑</el-button>
              <el-button link type="danger" @click="handleDeleteStaff(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 人员信息新增/编辑弹窗 -->
      <el-dialog
        :title="staffDialogTitle"
        v-model="staffDialogVisible"
        v-if="staffDialogVisible"
        :before-close="beforeClose"
        width="600px"
        append-to-body
        :close-on-click-modal="false"
      >
        <el-form
          ref="staffDialogFormRef"
          :model="staffDialogData"
          label-width="100px"
          :rules="staffRules"
          inline
        >
          <el-form-item label="人员类型" prop="type">
            <el-select
              v-model="staffDialogData.type"
              placeholder="请选择人员类型"
              style="width: 100%"
              class="!w50"
              clearable
            >
              <el-option
                v-for="item in staffTypes"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="姓名" prop="name">
            <el-input v-model="staffDialogData.name" placeholder="请输入姓名" />
          </el-form-item>

          <el-form-item label="性别" prop="gerden">
            <el-select
              v-model="staffDialogData.gerden"
              placeholder="请选择性别"
              style="width: 100%"
              clearable
              class="!w50"
            >
              <el-option label="男" :value="1" />
              <el-option label="女" :value="0" />
            </el-select>
          </el-form-item>
          <el-form-item label="身份证号" prop="identityCard">
            <el-input v-model="staffDialogData.identityCard" placeholder="请输入身份证号" />
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="staffDialogData.email" placeholder="请输入邮箱（选填）" />
          </el-form-item>
          <el-form-item label="手机号" prop="phone">
            <el-input v-model="staffDialogData.phone" placeholder="请输入手机号（选填）" />
          </el-form-item>
          <el-form-item label="是否在职" prop="isOnJob" class="!w70">
            <el-select
              v-model="staffDialogData.isOnJob"
              placeholder="请选择在职状态"
              style="width: 100%"
              clearable
            >
              <el-option label="是" :value="0" />
              <el-option label="否" :value="1" />
            </el-select>
          </el-form-item>

          <el-form-item label="证书附件" prop="attachment">
            <el-upload
              action="#"
              multiple
              :file-list="fileList2"
              :limit="5"
              :auto-upload="false"
              :before-upload="beforeUpload"
              :on-change="handleFileSelect2"
              :on-exceed="handleExceed"
              :on-preview="handlePreview"
              :accept="'image/png, image/jpeg, application/pdf, application/zip'"
              :on-remove="handleRemove2"
              :before-remove="beforeRemove2"
            >
              <template #tip>
                <div class="el-upload__tip">
                  请上传png、jpg、pdf、zip格式文件。大小不超过50M。
                </div>
              </template>
              <el-button type="primary">选择文件</el-button>
            </el-upload>
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="staffDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="handleStaffDialogSave">确定</el-button>
          </div>
        </template>
      </el-dialog>
    </el-card>
  </ContentWrap>
</template>

<script setup lang="ts">
import { OrganizationQualificationApi } from '@/api/qis/organizationqualification'
import { OrganizationStaffApi } from '@/api/qis/organizationstaff'
import { SampleInformationApi } from '@/api/qis/sampleinformation'
import { Plus } from '@element-plus/icons-vue'
// 暂时注释掉未使用的导入和变量
// import { OrganizationStaffApi } from '@/api/qis/organizationstaff'
// const route = useRoute()
const router = useRouter()
const message = useMessage()
const loading = ref(false)
const formRef = ref()
const sampleFormRef = ref()
const detailData = ref<any>({})

const qualificationList = ref([])


// 下载附件
const downloadFile=(link)=> {
  const fileExtension = link.split('.').pop().toLowerCase();
      if (['jpg', 'jpeg', 'png', 'gif', 'bmp','pdf'].includes(fileExtension)) {
        // 如果是图片，在新窗口打开预览
        window.open(link, '_blank');
      } else if (fileExtension === 'zip') {
        // 如果是 ZIP 压缩包，执行下载操作
        const a = document.createElement('a');
        a.href = link;
        a.download = link.split('/').pop();
        a.click();
        document.body.removeChild(a);
      } else {
        // 其他类型文件也执行下载操作
        const a = document.createElement('a');
        a.href = link;
        a.download = link.split('/').pop();
        a.click();
        document.body.removeChild(a);
      }
    }
  

// 弹窗相关
const dialogVisible = ref(false)
const dialogTitle = ref('')
const dialogFormRef = ref()
const dialogData = ref<any>({})

const fileList1 = ref([])
const tempFileList1 = ref<File[]>([]) // 临时存储待上传的机构资质文件
const tempFileList2 = ref<File[]>([]) // 临时存储待上传的人员附件文件

const sampleFormRules = {
  receiveName: [
    { required: true, message: '请输入联系人姓名', trigger: 'blur' },
    { max: 10, message: '联系人姓名长度不能超过10个字符', trigger: 'blur' },
    { pattern: /^[\u4e00-\u9fa5]+$/, message: '联系人姓名只能为中文', trigger: 'blur' }
  ],
  receivePhone: [
    { required: true, message: '请输入联系人电话', trigger: 'blur' },
    { max: 20, message: '联系人电话长度不能超过20个字符', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { max: 50, message: '邮箱长度不能超过50个字符', trigger: 'blur' }
  ],
  mailingAddress: [
    { required: true, message: '请输入通讯地址', trigger: 'blur' },
    { max: 50, message: '通讯地址长度不能超过50个字符', trigger: 'blur' }
  ]
}

const closeDialogJGZZ = () => {
  dialogVisible.value = false
  fileList1.value = []
  tempFileList1.value = []
}
// 机构人员信息下载
const handleDownloadStaff = (row) => {}

// 机构资质下载
const handleDownLoad1 = (row) => {
  console.log(row)
}
const fileList = ref([])
// 证书类型选项
const certificateTypes = [
  { value: 0, label: 'CMA' },
  { value: 1, label: 'CNAS' },
  { value: 2, label: '体系证书' }
]

// 表单校验规则
const rules = {
  type: [{ required: true, message: '请选择证书类型', trigger: 'change' }],
  num: [
    { required: true, message: '请输入证书编号', trigger: 'blur' },
    { max: 30, message: '证书编号长度不能超过30个字符', trigger: 'blur' }
  ],
  licenceIssuingAuthority: [
    { required: true, message: '请输入发证机关', trigger: 'blur' },
    { max: 30, message: '发证机关长度不能超过30个字符', trigger: 'blur' }
  ],
  issueDate: [{ required: true, message: '请选择发证日期', trigger: 'change' }],
  expireTime: [{ required: true, message: '请选择有效日期', trigger: 'change' }],
  attachment: [{ required: true, message: '请上传附件', trigger: 'change' }]
}

const rules1 = {
  managerPhone: [{ max: 30, message: '联系人电话长度不能超过30个字符', trigger: 'blur' }],
  summary: [{ max: 300, message: '描述长度不能超过300个字符', trigger: 'blur' }]
}
const fileList2 = ref([])

/** 处理文件超出限制 */
const handleExceed = (files: File[], uploadFiles: File[]) => {
  message.warning(`最多只能上传 5 个文件，当前已选择了 ${uploadFiles.length} 个文件`)
}

// 机构资质文件选择
const handleFileSelect1 = (file: any, fileList: any) => {
  console.log('File selected:', file, fileList)
  if (file.raw) {
    tempFileList1.value.push(file.raw)
    fileList1.value = fileList
  }
}

// 机构资质文件上传
const uploadFiles1 = async () => {
  // 如果是编辑模式，我们需要检查哪些文件被保留了
  if (dialogData.value.id) {
    // 获取当前显示的文件URL列表
    const currentFileUrls = fileList1.value
      .filter((file) => file.url && file.url.startsWith('http'))
      .map((file) => file.url)

    // 直接使用这些URL作为attachment，不需要重新上传已有的文件
    dialogData.value.attachment = currentFileUrls.join(';')
  } 

  // 只上传新添加的文件
  if (tempFileList1.value.length === 0) return true
  try {
    const uploadPromises = tempFileList1.value.map(async (file) => {
      const formData = new FormData()
      formData.append('file', file)
      const res = await SampleInformationApi.uploadFileApi(formData)
      return (window.configUrl.minIo?window.configUrl.minIo: 'http://182.151.214.104:8040') + res
    })

    const urls = await Promise.all(uploadPromises)
    // 将新上传的URL添加到现有URL中
    const currentUrls = dialogData.value.attachment
      ? dialogData.value.attachment.split(';').filter(Boolean)
      : []

    dialogData.value.attachment = [...currentUrls, ...urls].join(';')
    tempFileList1.value = []
    console.log('最终保存的附件:', dialogData.value.attachment)
    return true
  } catch (error) {
    console.error(error)
    // message.error('文件上传失败')
    return false
  }
}

// 人员附件文件选择
const handleFileSelect2 = (file: any, fileList: any) => {
  console.log('Staff file selected:', file, fileList)
  if (file.raw) {
    // 只在文件被添加时处理
    if (file.status === 'ready') {
      tempFileList2.value.push(file.raw)
    }
    // 更新文件列表，保留已有文件的URL，为新文件创建临时URL
    fileList2.value = fileList.map((f) => ({
      name: f.name || `附件${fileList2.value.length + 1}`,
      url: f.url || URL.createObjectURL(f.raw),
      uid: f.uid || new Date().getTime() + fileList2.value.length
    }))
  }
  console.log('当前文件列表:', fileList2.value)
}

// 人员附件文件上传
const uploadFiles2 = async () => {
  // 如果是编辑模式，我们需要检查哪些文件被保留了
  if (staffDialogData.value.id) {
    // 获取当前显示的文件URL列表
    const currentFileUrls = fileList2.value
      .filter((file) => file.url && file.url.startsWith('http'))
      .map((file) => file.url)

    // 直接使用这些URL作为attachment，不需要重新上传已有的文件
    staffDialogData.value.attachment = currentFileUrls.join(';')
  }

  // 只上传新添加的文件
  if (tempFileList2.value.length === 0) return true
  try {
    const uploadPromises = tempFileList2.value.map(async (file) => {
      const formData = new FormData()
      formData.append('file', file)
      const res = await SampleInformationApi.uploadFileApi(formData)
      return (window.configUrl.minIo ? window.configUrl.minIo : 'http://182.151.214.104:8040') + res
    })

    const urls = await Promise.all(uploadPromises)
    // 将新上传的URL添加到现有URL中
    const currentUrls = staffDialogData.value.attachment
      ? staffDialogData.value.attachment.split(';').filter(Boolean)
      : []

    staffDialogData.value.attachment = [...currentUrls, ...urls].join(';')
    tempFileList2.value = []
    console.log('最终保存的附件:', staffDialogData.value.attachment)
    return true
  } catch (error) {
    console.error(error)
    // message.error('文件上传失败')
    return false
  }
}

// 保留原有的handleFileChange函数以保持兼容性
const handleFileChange = async (file: File) => {
  // 兼容旧版本的调用
  const mockEvent = {
    raw: file,
    status: 'ready'
  }
  handleFileSelect2(mockEvent, [mockEvent])
}
// 重置弹窗数据
const resetDialogData = () => {
  dialogData.value = {}
}
const route = useRoute()
/** 获取详情 */
const getDetail = async () => {
  try {
    loading.value = true
    // 在实际项目中，这里需要调用后端API获取数据
    const id = route.query.id as unknown as number
    const data = await OrganizationQualificationApi.getOrganizationQualification(id)
    detailData.value = data
    const url = data.attachment
    // const url1 = data.attachment
    // console.log(detailData.value, 'detail')
    // fileList1.value.push({
    //   uid: new Date().getTime(), // 生成唯一的 uid
    //   name: url.split('/').pop(), // 从 URL 中提取文件名
    //   url: url
    // })
    // qualificationList.value = await OrganizationStaffApi.getQualifications(id)
  } finally {
    loading.value = false
  }
}

// 获取机构资质列表
const getJiGouZz = async () => {
  const res = await OrganizationStaffApi.getOrganizationStaffPage({
    pageNo: 1,
    pageSize: 100,
    orgId: route.query.id
  })
  console.log(res)
  qualificationList.value = res.list
}

/** 保存操作 */
const handleSave = async () => {
  console.log('baocun')
  console.log(sampleFormRef.value, 'sampleFormRef')
  if (!sampleFormRef.value) return
  await sampleFormRef.value.validate(async (valid) => {
    console.log(valid)
    if (valid) {
      console.log('1111') // 修改
      if (route.query.id) {
        try {
          loading.value = true
          // TODO: 调用保存接口
          await OrganizationQualificationApi.updateOrganizationQualification(detailData.value)
          message.success('保存成功')
        } finally {
          loading.value = false
        }
      } else {
        try {
          // 新增
          await OrganizationQualificationApi.updateOrganizationQualification(detailData.value)
        } catch (error) {
          // message.error('保存失败')
        } finally {
          loading.value = false
        }
      }
    }
  })
}

/** 返回操作 */
const handleBack = () => {
  router.back()
}

/** 新增操作 */
const handleAddZz = () => {
  dialogTitle.value = '新增机构资质'
  dialogVisible.value = true
  fileList1.value = []
  resetDialogData()
}

/** 编辑操作 */
const handleEdit = (row: any) => {
  dialogTitle.value = '编辑机构资质'
  fileList1.value = []
  tempFileList1.value = []
  dialogVisible.value = true
  console.log(row, 'row')
  dialogData.value = { ...row }
  // 保存原始附件信息，用于跟踪哪些文件被删除了
  dialogData.value.originalAttachment = dialogData.value.attachment
  console.log(dialogData, 'dialogData')
  console.log(dialogData.value.attachment.split(';'))
  const fileArr = dialogData.value.attachment.split(';').filter(Boolean)
  fileList1.value = fileArr.map((file, index) => ({
    url: file,
    name: `附件${index + 1}`,
    uid: new Date().getTime() + index
  }))
  console.log(fileList1.value, 'fileList1.value') // 打印 fileList1.value 确认内容
}

const handlePreview = (file) => {
  console.log(file, 'file')
  const imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'svg', 'pdf']
  const fileExtension = file.url.split('.').pop().toLowerCase()
  if (imageExtensions.includes(fileExtension)) {
    // 如果是图片，在新窗口中打开
    window.open(file.url, '_blank')
  } else {
    // 不是图片，进行文件下载
    const a = document.createElement('a')
    const url = file.url
    a.download = file.name
    a.href = url
    a.click()
  }
}

/** 删除操作 */
const handleDelete = async (row: any) => {
  try {
    await message.confirm('是否确认删除该资质？')
    await OrganizationStaffApi.deleteJgryApi(row.id)
    getJgrypage()
  } catch {}
}

/** 删除操作 */
const handleDelete1 = async (row: any) => {
  try {
    await message.confirm('是否确认删除该资质？')
    await OrganizationQualificationApi.deleteJgzz(row.id)
    getJiGouZz()
  } catch {}
}

const imgUrl = ref('')

/**   机构资质上传文件上传改变事件 */
const handleFileChange1 = (file: any, fileList: any) => {
  console.log('File selected:', file, fileList)
  if (file.raw) {
    // 只在文件被添加时处理
    if (file.status === 'ready') {
      tempFileList1.value.push(file.raw)
    }
    // 更新文件列表，保留已有文件的URL，为新文件创建临时URL
    fileList1.value = fileList.map((f) => ({
      name: f.name || `附件${fileList1.value.length + 1}`,
      url: f.url || URL.createObjectURL(f.raw),
      uid: f.uid || new Date().getTime() + fileList1.value.length
    }))
  }
  console.log('当前文件列表:', fileList1.value)
}

// 删除机构资质上传文件
const beforeRemove1 = (uploadFile: UploadFile) => {
  return ElMessageBox.confirm(`确定移除 ${uploadFile.name}？`)
}

const beforeRemove2 = (uploadFile: UploadFile, uploadFiles: UploadFiles) => {
  console.log(uploadFile, 'uploadFile')
  console.log(uploadFiles, 'uploadFiles')
  fileList2.value = fileList2.value.filter((item) => {
    if (item.uid === uploadFile.uid) {
      console.log(item)
    }
    return item.uid !== uploadFile.uid
  })

  console.log(fileList1.value, 'fileList1')
}

// 机构人员信息上传文件上传改变事件
// const handleFileChange = async (target: any) => {
//   // const fileDataFile = new FormData()
//   // fileDataFile.append('file', target.file)

//   // const res = await SampleInformationApi.uploadFileApi(fileDataFile)
//   // imgUrl.value = res
//   // console.log('🚀 ~ handleFileChange ~ fileList1:', fileList1)
//   // // console.log(res.data,'res.data')
//   // // console.log(imgUrl.value,'imgUrl')
//   // staffDialogData.value.attachment = 'http://192.168.2.241:8040' + imgUrl.value
//   // message.success('上传成功')

//   console.log('target', target)

// const fileDataFile = new FormData()
// fileDataFile.append('file', target.file)

// const res = await SampleInformationApi.uploadFileApi(fileDataFile)
// imgUrl.value = res
// // imgUrl.value = 'http://192.168.2.241:8040' + imgUrl.value
// imgUrl.value = 'http://182.151.214.104:8040' + imgUrl.value

// fileList2.value.push(imgUrl.value)

// const newArr = fileList2.value.map((item)=>{
//     if(Object.prototype.toString.call(item) === '[object Object]'){
//         console.log('item',item)
//         return item.url
//       }else {
//         return imgUrl.value
//       }
//   })

// console.log(fileList2.value, 'fileList2')
// staffDialogData.value.attachment = newArr.join(';')
// console.log(staffDialogData.value.attachment, 'staffDialogData.value.attachment')
// message.success('上传成功')
// }

// 移除机构资质文件
const handleRemove = (uploadFile: UploadFile, uploadFiles: UploadFiles) => {
  console.log(uploadFile.url, 'uploadFile')
  const urlArray = dialogData.value.attachment.split(';')
  const filteredArray = urlArray.filter((item) => item !== uploadFile.url)
  dialogData.value.attachment = filteredArray.join(';')

  fileList1.value.filter((item) => {
    return item !== uploadFile.url
  })
  console.log(fileList1.value, 'fileList1')
}

// 删除人员附件上传文件
const handleRemove2 = (uploadFile: UploadFile, uploadFiles: UploadFiles) => {
  fileList2.value = uploadFiles

  // 从临时文件列表中移除
  const index = tempFileList2.value.findIndex((file) => file.name === uploadFile.name)
  if (index !== -1) {
    tempFileList2.value.splice(index, 1)
  }

  // 从已上传文件中移除
  if (staffDialogData.value.attachment) {
    const attachments = staffDialogData.value.attachment.split(';').filter(Boolean)
    const updatedAttachments = attachments.filter((url) => !url.includes(uploadFile.name))
    staffDialogData.value.attachment = updatedAttachments.join(';')
  }
}

// const handleRemove1 = (uploadFile: UploadFile, uploadFiles: UploadFiles)=>{
//   console.log(uploadFile.url, 'uploadFile')
// const urlArray = staffDialogData.value.attachment.split(';')
// const filteredArray = urlArray.filter(item => item !== uploadFile.url)
// staffDialogData.value.attachment = filteredArray.join(';')
// console.log(uploadFile.url)
//   const newFile =  fileList2.value.map(item=>{
//   console.log(item)
//   return item !== uploadFile.url
// })
// console.log(newFile,'newFile')
// }

// 删除机构资质上传文件
const handleRemove1 = (uploadFile: UploadFile, uploadFiles: UploadFiles) => {
  console.log('Removing qualification file:', uploadFile)

  // 更新显示的文件列表
  fileList1.value = uploadFiles

  // 从临时文件列表中移除被删除的文件（如果是新上传的）
  const index = tempFileList1.value.findIndex((file) => file.name === uploadFile.name)
  if (index !== -1) {
    tempFileList1.value.splice(index, 1)
  }

  // 如果文件已经上传过，从 dialogData 中也移除
  if (dialogData.value.attachment) {
    const attachments = dialogData.value.attachment.split(';').filter(Boolean)
    const updatedAttachments = attachments.filter((url) => {
      // 检查文件名是否匹配
      const fileName = url.split('/').pop()
      return fileName !== uploadFile.name
    })
    dialogData.value.attachment = updatedAttachments.join(';')
  }

  // 如果所有文件都被删除，清空 attachment
  if (uploadFiles.length === 0) {
    dialogData.value.attachment = ''
  }

  console.log('Updated attachment:', dialogData.value.attachment)
}

/** 保存弹窗数据 */
const handleDialogSave = async () => {
  console.log(dialogData.value, 'dialogData.value')

  // 先上传文件
  const uploadSuccess = await uploadFiles1()
  if (!uploadSuccess) {
    message.error('文件上传失败，请重试')
    return
  }

  if (!dialogFormRef.value) return
  await dialogFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      try {
        loading.value = true

        // 保存数据
        dialogData.value.orgId = route.query.id as unknown as number
        if (dialogData.value.id) {
          const res = await OrganizationStaffApi.updateOrganizationStaff(dialogData.value)
          console.log(res, 'xiugai')
        } else {
          // 新增
          const res = await OrganizationStaffApi.createOrganizationStaff(dialogData.value)
          console.log(res, 'chuangjian ')
        }
        message.success('保存成功')
        dialogVisible.value = false
        getJiGouZz()
        getJgrypage()
      } catch (error) {
        console.error(error)
        // message.error('保存失败')
      } finally {
        loading.value = false
      }
    }
  })
}

// 人员信息相关
const staffDialogVisible = ref(false)
const staffDialogTitle = ref('')
const staffDialogFormRef = ref()
const staffDialogData = ref({
  isOnJob: 0,
  type: '',
  name: '',
  gender: '',
  idNumber: '',
  email: '',
  phone: '',
  isActive: true,
  attachment: ''
})

// 人员类型选项
const staffTypes = [
  { value: 0, label: '机构管理员' },
  { value: 1, label: '抽样人员' },
  { value: 2, label: '检验人员 ' },
  { value: 3, label: '技术审批人' }
]

// 示例数据
const staffList = ref([])

// 人员表单校验规则
const staffRules = {
  type: [{ required: true, message: '请选择人员类型', trigger: 'change' }],
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' },
    { max: 10, message: '姓名长度不能超过10个字符', trigger: 'blur' },
    { pattern: /^[\u4e00-\u9fa5]+$/, message: '姓名只能为中文', trigger: 'blur' }
  ],
  gerden: [{ required: true, message: '请选择性别', trigger: 'change' }],
  identityCard: [
    { required: true, message: '请输入身份证号', trigger: 'blur' },
    {
      pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/,
      message: '请输入正确的身份证号',
      trigger: 'blur'
    }
  ],
  email: [{ type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' },
    { max: 20, message: '手机号长度不能超过20个字符', trigger: 'blur' }
  ],
  isOnJob: [{ required: true, message: '请选择在职状态', trigger: 'change' }],
  attachment: [{ required: true, message: '请上传附件', trigger: 'change' }]
}

// 重置人员弹窗数据
const resetStaffDialogData = () => {
  staffDialogData.value = {
    type: '',
    name: '',
    gender: '',
    idNumber: '',
    email: '',
    phone: '',
    isActive: true,
    attachment: '',
    isOnJob: 0
  }
}

/** 新增人员操作 */
const handleAddStaff = () => {
  staffDialogTitle.value = '新增人员信息'
  staffDialogVisible.value = true
  fileList2.value = []
  resetStaffDialogData()
}

/** 编辑人员操作 */
const handleEditStaff = (row: any) => {
  fileList2.value = []
  console.log(row)
  staffDialogTitle.value = '编辑人员信息'
  staffDialogVisible.value = true
  staffDialogData.value = { ...row }
  // 保存原始附件信息，用于跟踪哪些文件被删除了
  staffDialogData.value.originalAttachment = staffDialogData.value.attachment

  if (staffDialogData.value.attachment) {
    const fileArr = staffDialogData.value.attachment.split(';').filter(Boolean)
    console.log(fileArr, 'fileArr')
    fileList2.value = fileArr.map((file, index) => {
      return {
        url: file,
        name: `附件${index + 1}`,
        uid: new Date().getTime() + index
      }
    })
  }
  // 重置临时文件列表
  tempFileList2.value = []
}

/** 删除人员操作 */
const handleDeleteStaff = async (row: any) => {
  try {
    await message.confirm('是否确认删除该人员？')
    await OrganizationStaffApi.deleteJgryApi(row.id)
    getJgrypage()
  } catch {}
}

/** 查看人员附件 */
const handleViewStaffFile = () => {
  message.info('查看附件功能开发中')
}

/** 人员文件上传改变事件 */
const handleStaffFileChange = (file: any, fileList: any) => {
  const current = fileList.map((item) => item.url)
  staffDialogData.value.attachment = current.join(';')
}

/** 保存人员弹窗数据 */
const handleStaffDialogSave = async () => {
  // 检查当前显示的文件列表
  const currentFileCount = fileList2.value.length
  const newFileCount = tempFileList2.value.length

  // 验证是否有文件
  if (currentFileCount === 0 && newFileCount === 0) {
    message.warning('请上传证书附件')
    return
  }

  // 先上传文件
  const uploadSuccess = await uploadFiles2()
  if (!uploadSuccess) {
    message.error('文件上传失败，请重试')
    return
  }

  console.log('最终保存的附件:', staffDialogData.value.attachment)

  staffDialogData.value.orgId = route.query.id
  if (!staffDialogFormRef.value) return

  await staffDialogFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      try {
        if (!staffDialogData.value.id) {
          const res = await OrganizationStaffApi.createJgryApi(staffDialogData.value)
          console.log(res, '新增机构人员')
          message.success('新增成功')
        } else {
          const res = await OrganizationStaffApi.updateJgryApi(staffDialogData.value)
          console.log(res, '更新机构人员')
          message.success('更新成功')
        }
        staffDialogVisible.value = false
        await getJgrypage()
        resetFile()
      } catch (error) {
        console.error('保存失败:', error)
        // message.error('保存失败，请重试')
      }
    }
  })
}

// 获取机构人员分页
const getJgrypage = async () => {
  const res = await OrganizationStaffApi.getJgrypageApi({
    pageNo: 1,
    pageSize: 100,
    orgId: route.query.id
  })
  staffList.value = res.list
  console.log(staffList.value, 'staffList.value')
}

function getFileExtension(fileName) {
  return fileName.slice(((fileName.lastIndexOf('.') - 1) >>> 0) + 2)
}

// 文件限制

const beforeUpload = (file, isShowMessage = true) => {
  const baseSize = 50
  // const isAllowedType = ['image/png', 'image/jpeg', 'application/pdf', 'application/zip'].includes(file.type);
  const allowedTypes = ['image/png', 'image/jpeg', 'application/pdf', 'application/zip']
  const allowedExtensions = ['png', 'jpg', 'jpeg', 'pdf', 'zip']

  const fileExtension = getFileExtension(file.name)
  const isAllowedType =
    allowedTypes.includes(file.type) || allowedExtensions.includes(fileExtension)

  if (!isAllowedType) {
    message.error('请上传 png、jpg、pdf、zip 格式的文件。')
    return false
  }
  // if (!isAllowedType) {

  //       message.error('请上传png、jpg、pdf、zip格式的文件。');
  //       return false;
  //     }
  const maxSize = baseSize * 1024 * 1024 // 50MB
  if (file.size > maxSize) {
    isShowMessage && message.warning(`文件大小不能超过 ${baseSize}MB`)
    return false
  }

  return true
}

const beforeClose = () => {
  console.log('jinlail ')
  resetFile()
}
// 重置图片和相关数据
const resetFile = () => {
  fileList1.value = []
  fileList2.value = []
  tempFileList1.value = []
  tempFileList2.value = []

  // 清空对话框数据
  dialogData.value = {}
  staffDialogData.value = {}

  // 关闭对话框
  dialogVisible.value = false
  staffDialogVisible.value = false
}

/** 初始化 */
onMounted(() => {
  getDetail()
  getJiGouZz()
  getJgrypage()

  if(route.query.id){
    route.meta.title = '编辑承检机构管理'
  }else {
    route.meta.title = '新增承检机构管理'
  }
})
</script>

<style lang="scss" scoped>
.mb-4 {
  margin-bottom: 1rem;
}

.mt-4 {
  margin-top: 1rem;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.right-button {
  .el-button {
    margin-left: 12px;
  }
}

.attachment-container {
  display: flex;
  flex-wrap: wrap;
}

.attachment-container span {
  margin: 0 2px; /* 给每个附件链接之间添加一点间距 */
}

</style>
